package com.hyz.user.service.impl;

import com.hyz.common.pojo.Order;
import com.hyz.common.pojo.User;
import com.hyz.common.response.OrderVO;
import com.hyz.common.response.Result;
import com.hyz.common.response.UserOrdersVO;
import com.hyz.user.feign.OrderApi;
import com.hyz.user.mapper.UserMapper;
import com.hyz.user.service.UserService;
import org.dozer.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderApi orderApi;
    @Autowired
    private Mapper mapper;

//    根据用户名查询用户信息
    @Override
    public User findUserById(String username) {
        return userMapper.selectByPrimaryKey(username);
    }

//    根据用户登录名查询订单列表
    @Override
    public UserOrdersVO findOrderByUserId(String username) {
        //参数为空
        if (StringUtils.isEmpty(username)) {

        }
//        查询用户信息
        User user = this.findUserById(username);
        //对对象进行非空判断
        Optional<User> optional = Optional.ofNullable(user);
        if(!optional.isPresent())
            throw new RuntimeException("查无此人");
        //将pojo转换成为vo
        UserOrdersVO userOrdersVO = new UserOrdersVO();
        BeanUtils.copyProperties(optional.get(),userOrdersVO);

        //查询订单列表
        List<Order> orders = orderApi.findOrderByUserId(username);
        //将pojo转换成为vo
        List<OrderVO> orderVOS = orders.stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            mapper.map(order, orderVO);
            return orderVO;
        }).collect(Collectors.toList());
        userOrdersVO.setOrders(orderVOS);
        return userOrdersVO;
    }

//    根据条件查询用户所属订单列表
    @Override
    public UserOrdersVO findOrders(String username) {
        return null;
    }
}
